package com.lkd.http.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.ConvertUtils;
import com.lkd.vo.PayVO;
import com.lkd.wxpay.WXConfig;
import com.lkd.wxpay.WxPayDTO;
import com.lkd.wxpay.WxPaySDKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {


    @Autowired
    private  WxPaySDKUtil wxPaySDKUtil;

    @Autowired
    private OrderService orderService;


    /**
     * 微信小程序支付
     * @param   payVo
     * @return
     */
    @PostMapping("weixinpay")
    public  String weixinPay(@RequestBody PayVO payVo){
        //创建订单
        OrderEntity orderEntity = orderService.createOrder(payVo);
        //封装支付请求对象调用支付
        WxPayDTO wxPayDTO = new WxPayDTO();
        wxPayDTO.setOpenid(orderEntity.getOpenId());
        wxPayDTO.setOutTradeNo(orderEntity.getOrderNo());
        wxPayDTO.setBody(orderEntity.getSkuName());
        wxPayDTO.setTotalFee(orderEntity.getAmount());
        return  wxPaySDKUtil.requestPay(wxPayDTO);
    }


    /**
     * 微信支付回调接口
     * @param request
     * @return
     */
    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response){
        log.info("调用了回调方法");
        //输入流转换为xml字符串
        orderService.vendOut("01000002205579467466900");
     /*   try {
            String notifyResult = ConvertUtils.convertToString( request.getInputStream() );
            String orderSn = wxPaySDKUtil.validPay(notifyResult);
            if(orderSn!=null){
                log.info("回调成功");
                orderService.vendOut(orderSn);
                //给微信支付一个成功的响应
                response.setContentType("text/xml");
                response.getWriter().write(WXConfig.RESULT);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }
}
